package com.chen.demoa.utils;

import io.seata.common.util.StringUtils;
import org.apache.commons.lang.BooleanUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class XssFilter implements Filter {
    private static boolean IS_INCLUDE_RICH_TEXT = false;//用于接收配置中的参数，决定这个过滤器是否开启
    public List<String> excludes = new ArrayList<String>();//用于接收配置中的参数，决定哪些是不需要过滤的url（在这里，也可以修改handleExcludeURL（）方法中相应的代码，使其变更为只需要过滤的url）
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        if (handleExcludeURL(req, resp)) {
            chain.doFilter(request, response);
            return;
        }
        XssHttpServletRequestWrapper xssRequest = new XssHttpServletRequestWrapper((HttpServletRequest) request);
        chain.doFilter(xssRequest, response);
    }
    /**
     *此方法是决定对当前url是否执行过滤，
     *在这里没有使用请求方法（post/put）来匹配，因为在本项目中使用url匹配更适合（因为get和其他请求方式也需要进行过滤），如果你有兴趣可以把这个方法更改为匹配请求方法进行过滤
     **/
    private boolean handleExcludeURL(HttpServletRequest request, HttpServletResponse response) {
        if ((excludes == null || excludes.isEmpty())&&IS_INCLUDE_RICH_TEXT) {
            return false;
        }
        String url = request.getServletPath();
        for (String pattern : excludes) {
            Pattern p = Pattern.compile("^" + pattern);
            Matcher m = p.matcher(url);
            if (m.find()) {
                return true;
            }
        }
        return false;
    }
    /**
     *过滤器初始化，从配置类中获取参数，用于初始化两个参数（是否开启，排除指定的url list）
     *
     */
    @Override
    public void init(FilterConfig arg0) throws ServletException {
        String isIncludeRichText = arg0.getInitParameter("isIncludeRichText");
        if (StringUtils.isNotBlank(isIncludeRichText)) {
            IS_INCLUDE_RICH_TEXT = BooleanUtils.toBoolean(isIncludeRichText);
        }

        String temp = arg0.getInitParameter("excludes");
        if (temp != null) {
            String[] url = temp.split(",");
            for (int i = 0; url != null && i < url.length; i++) {
                excludes.add(url[i]);
            }
        }
    }

    @Override
    public void destroy() {
    }

}
